﻿using System;
using System.Threading.Tasks;

using Agile;
using Agile.Service;
using Agile.Service.Rbac;

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Web.Controllers {
    /// <summary>
    /// 登录
    /// </summary>
    [AllowAnonymous]
    public class LoginController:Controller {
        private readonly VerifyCode _verifyCode;
        private readonly IUserService _userService;
        private readonly ApplicationSettings _applicationSettings;
        private readonly IAuth _auth;
        private string chkCode;
        public LoginController(IAuth auth,VerifyCode verifyCode,
            IUserService userService,
            ApplicationSettings applicationSettings) {
            _auth = auth;
            _verifyCode = verifyCode;
            _userService = userService;
            _applicationSettings = applicationSettings;
        }
        [HttpGet]
        [AllowAnonymous]
        public IActionResult Index(string returnUrl) {
            if(User.Identity.IsAuthenticated) {
                return View("Error",new string[] { "您已经登录！" });
            }
            ViewBag.returnUrl = returnUrl;
            return View(_applicationSettings);
        }
        [HttpGet]
        public ActionResult GetAuthCode() {
            var bytes = _verifyCode.GetVerifyCode(out chkCode);
            return File(bytes,@"image/Gif");
        }
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> CheckLogin(string username,string password,string code) {
            try {
                var sessionCode = ConfigurationHelper.GetValue<string>("agile_session_verifycode");
                if(string.IsNullOrEmpty(code)) {
                    return Content(new Result { Success = false,StatusCode = 500,Message = "请输入验证码" }.ToJson());
                }
                if(sessionCode != code.Trim().ToLower()) {
                    return Content(new Result { Success = false,StatusCode = 500,Message = sessionCode + "验证码错误，请重新输入" }.ToJson());
                }
                var result = await _auth.LoginAsync(username,password);
                return Content(result.ToJson());
            } catch(Exception ex) {
                return Content(new Result { Success = false,StatusCode = 500,Message = "登录失败，" + ex.Message }.ToJson());
            }
        }
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> OutLogin() {
            await _auth.LogoutAsync();
            return Redirect("/Login");
        }
    }
}